from http.client import responses
from django.http import JsonResponse
from detect.src.forms.uploadForm import uploadForm
from django.http import HttpResponse, request
from django.shortcuts import render, redirect
from detect.models import UserImage
from PIL import Image
def uploadView(req):
    if req.method == 'GET':
        form = uploadForm()
        return render(req, 'detect/upload.html', {'form': form})
    elif req.method == 'POST':
        # file = req.FILES.get('Images')
        # img = Image.open(file)
        # # Save the image
        # img.save('./saved_image.png')
        # with open(file.name, 'wb') as f:
        #         f.write()
        form = uploadForm(req.POST, req.FILES)
        if form.is_valid():
            user = form.cleaned_data['UserId']
            images = req.FILES.getlist('Images')
            for image in images:
                form = uploadForm(data={'UserId':user},files={'Images':image})
                form.save()
                print('Image saved')
            return HttpResponse("上传成功！")
        else:
            return HttpResponse(f"错误: {form.errors}")
            # images = req.FILES.getlist('Images')
            # user = req.POST.get('UserId')
            # for image in images:
            #    print('进入图片循环')
            #    form = uploadForm.uploadForm(data={'UserId':user},files={'Images':image})
            #    if form.is_valid():
            #        form.save()
            #        print('Image saved')
            #    else:
            #        print(form.errors)  # 打印错误
            #        return HttpResponse(form.errors)  # 显示哪个字段出错
            #    # form.save()
            # return HttpResponse("上传成功")
    return redirect('/detect/upload')

def hintbox(req):
    q = req.GET.get('q')
    userId = UserImage.objects.filter(UserId__contains=q).values_list("UserId",flat=True)[:3]
    return JsonResponse(list(userId), safe=False)



